//
//  KKImageLibrary.m
//  KKImagePickerController
//
//  Created by Mac mini on 16/1/21.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKImageLibraryManager.h"

#import "KKImagePickerManager.h"

@interface KKImageLibraryManager() {
    
    NSMutableArray *_groupItemArray;
    NSMutableArray *_assetItemArray;
    
    ALAssetsLibrary *_kk_assetsLibrary;
}

@end

@implementation KKImageLibraryManager

+ (instancetype)kk_defaultManager {
    
    static KKImageLibraryManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKImageLibraryManager new];
    });
    return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _groupItemArray = [NSMutableArray array];
        _assetItemArray = [NSMutableArray array];
    }
    return self;
}

#pragma mark - Private methods

#pragma mark - Public methods
- (void)kk_searchAllGroupsFromLibrary:(KKImageLibraryManagerAllGroupsHandle)handle {
    
    if (KKDeviceVersion < 8.0) {
        
        _kk_assetsLibrary = [ALAssetsLibrary new];
        [_groupItemArray removeAllObjects];
        
        __weak ALAssetsLibrary* weakAssetsLibrary = _kk_assetsLibrary;
        __weak NSMutableArray* weakGroupArray = _groupItemArray;
        
        ALAssetsLibraryGroupsEnumerationResultsBlock listGroupResultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
            
            if (group) {
                
                if ([[group valueForProperty: ALAssetsGroupPropertyType] integerValue] == ALAssetsGroupSavedPhotos) {
                    
                    KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetsGroup: group];
                    
                    [weakGroupArray insertObject: item atIndex: 0];
                }
                else {
                    
                    KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetsGroup: group];
                    
                    [weakGroupArray addObject: item];
                }
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if (handle) {
                        handle(weakGroupArray);
                    }
                });
            }
        };
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [weakAssetsLibrary enumerateGroupsWithTypes: ALAssetsGroupAll usingBlock: listGroupResultsBlock failureBlock:^(NSError *error) {
                NSLog(@"Group not found!\n");
                
                [KKImagePickerController kk_showErrorMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限"];
            }];
        });
    }
    else {
//        PHPhotoLibrary
        
//        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
//        
//        NSLog(@"smartAlbums = %@", smartAlbums);
        
        // 列出所有相册智能相册
        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
        
        // 列出所有用户创建的相册
        PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
        
        NSLog(@"smartAlbums = %@", smartAlbums);
        NSLog(@"topLevelUserCollections = %@", topLevelUserCollections);
        
        // 获取所有资源的集合，并按资源的创建时间排序
        PHFetchOptions *options = [[PHFetchOptions alloc] init];
        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
        
        // 在资源的集合中获取第一个集合，并获取其中的图片
        PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
        PHAsset *asset = assetsFetchResults[0];
        [imageManager requestImageForAsset:asset
                                targetSize: CGSizeMake(100, 100)
                               contentMode:PHImageContentModeAspectFill
                                   options:nil
                             resultHandler:^(UIImage *result, NSDictionary *info) {
                                 
                                 // 得到一张 UIImage，展示到界面上
                                 
                             }];
    }
}

- (void)kk_searchAllItemsFromLibraryWithGroup:(ALAssetsGroup *)group result:(KKImageLibraryManagerAllItemsOfGroupHandle)handle {
    
    [_assetItemArray removeAllObjects];
    __weak NSMutableArray* weakAssetItems = _assetItemArray;
    
    if (KKDeviceVersion < 8.0){
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                
                if (result) {
                    [weakAssetItems addObject: result];
                }
                else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if (handle) {
                            handle(weakAssetItems);
                        }
                    });
                }
            }];
        });
    }
    else {
        
    }
}

@end



@implementation KKImageLibraryGroupItem

- (UIImage *)kk_posterImage {
    return [UIImage imageWithCGImage: _kk_assetsGroup.posterImage];
}

- (NSInteger)kk_count {
    return _kk_assetsGroup.numberOfAssets;
}

- (NSString *)kk_groupName {
    return [_kk_assetsGroup valueForProperty: ALAssetsGroupPropertyName];
}

- (instancetype)initWithAssetsGroup:(ALAssetsGroup *)assetsGroup {
    self = [super init];
    if (self) {
        _kk_assetsGroup = assetsGroup;
    }
    return self;
}

@end